#!/usr/bin/env python3
import os
import shutil
from pathlib import Path

def create_deployment():
    # 使用绝对路径确保路径正确
    base_dir = Path(__file__).parent  # deploy.py所在目录（pybind_version）
    deploy_dir = base_dir / "deploy"
    
    # 创建部署目录（带父目录自动创建）
    deploy_dir.mkdir(parents=True, exist_ok=True)
    
    # 创建子目录
    bin_dir = deploy_dir / "bin"
    lib_dir = deploy_dir / "lib"
    rules_dir = deploy_dir / "rules"
    bin_dir.mkdir(parents=True, exist_ok=True)
    lib_dir.mkdir(parents=True, exist_ok=True)
    rules_dir.mkdir(parents=True, exist_ok=True)

    # 复制可执行文件
    build_dir = base_dir / "build"
    exe_paths = [
        build_dir / "bin" / "Release" / "run_drc.exe",
        build_dir / "bin" / "Debug" / "run_drc.exe",
        build_dir / "run_drc.exe"
    ]
    
    found_exe = None
    for path in exe_paths:
        if path.exists():
            found_exe = path
            break
            
    if not found_exe:
        print("搜索路径：")
        for p in exe_paths:
            print(f"- {p}")
        raise FileNotFoundError("找不到可执行文件，请先编译项目")
    
    shutil.copy2(found_exe, bin_dir)
    
    # 复制Python模块
    pyd_paths = [
        build_dir / "lib" / "Release" / "drc_core_python.cp312-win_amd64.pyd",
        build_dir / "lib" / "Debug" / "drc_core_python.cp312-win_amd64.pyd"
    ]
    
    found_pyd = None
    for path in pyd_paths:
        if path.exists():
            found_pyd = path
            break
    
    if not found_pyd:
        raise FileNotFoundError("找不到Python模块，请先编译项目")
    
    shutil.copy2(found_pyd, lib_dir)
    
    # 复制规则文件
    rules_src = base_dir / "rules"  # 源规则目录
    if not rules_src.exists():
        raise FileNotFoundError(f"找不到规则目录：{rules_src}")
        
    # 复制所有.py文件到规则目录
    for rule_file in rules_src.glob("*.py"):
        print(f"复制规则文件：{rule_file.name}")
        shutil.copy2(rule_file, rules_dir)
    
    # 创建启动脚本
    with open(deploy_dir / "run.bat", "w", encoding='utf-8') as f:
        f.write('@echo off\n')
        f.write('set PYTHONPATH=%~dp0lib;%~dp0rules\n')
        f.write('set PATH=%~dp0bin;%PATH%\n')
        f.write('cd %~dp0\n')
        f.write('bin\\run_drc.exe %*\n')
        f.write('pause\n')

    print(f"\n部署完成！目录结构：")
    print(f"{deploy_dir}/")
    print("├── bin/        # 可执行文件")
    print("├── lib/        # Python模块")
    print("├── rules/      # DRC规则文件")
    print("└── run.bat     # 启动脚本")

if __name__ == "__main__":
    create_deployment() 